/**
 * Created by yangxin on 2017/4/26.
 */
import axios from 'axios'
import utils from 'commons/utils'
import env from 'commons/env'
import { querystring } from 'vux'
import EventBus from 'eventbusjs'

import * as constants from 'src/AppConstants'

import Store from 'store'

axios.defaults.baseURL = env.API_BASE
axios.defaults.timeout = process.env.NODE_ENV !== 'production' ? 1000 * 60 * 10 : 1000 * 60
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

/**
 * 序列化对象为http标准的请求参数
 * @param reqParams 参数对象
 * @return {{}}
 */
const serializeParams = function(reqParams) {
    let params = {}
    for (let k1 in reqParams) {
        let v1 = reqParams[k1]
        if (Array.isArray(v1)) {
            for (let i = 0; i < v1.length; i++) {
                let v2 = v1[i]
                if (typeof(v2) == 'object') {
                    for (let k2 in v2) {
                        let v3 = v2[k2]
                        if (Array.isArray(v3)) {
                            for (let j = 0; j < v3.length; j++) {
                                params[`${k1}[${i}].${k2}[${j}]`] = v3[j]
                            }
                        } else {
                            params[`${k1}[${i}].${k2}`] = v3
                        }
                    }
                } else {
                    params[`${k1}[${i}]`] = v2
                }
            }
        } else if (typeof(v1) == 'object') {
            for (let k2 in v1) {
                let v2 = v1[k2]
                if (Array.isArray(v2)) {
                    for (let i = 0; i < v2.length; i++) {
                        params[`${k1}.${k2}[${i}]`] = v1[k2][i]
                    }
                } else if (typeof(v2) == 'object') {
                    for (let k3 in v2) {
                        let v3 = v1[k2][k3]
                        params[`${k1}.${k2}.${k3}`] = v3
                    }
                } else {
                    params[`${k1}.${k2}`] = v1[k2]
                }
            }
        } else {
            params[k1] = v1
        }
    }
    return params
}

// 请求拦截
axios.interceptors.request.use(function(config) {
    if (!config.headers[constants.HIDE_LOADING_FLAG] || config.headers[constants.HIDE_LOADING_FLAG] === false) {
        Store.dispatch('showLoading', true)
    } else {
        delete config.headers[constants.HIDE_LOADING_FLAG]
    }
    config.headers.common[constants.API_TOKEN] = Store.state.token
    let sign
    if (config.method == 'get') {
        config.params = serializeParams(config.params) // 序列化请求参数
        config.params['timestamp'] = new Date().getTime()
        sign = utils.getSign(config.params)
        if (sign) {
            config.params[constants.PARAM_SIGN_NAME] = sign
        }
    } else if (config.method == 'delete') {
        config.params = config.params || {}
        config.params['timestamp'] = new Date().getTime()
        sign = utils.getSign(config.params)
        config.params[constants.PARAM_SIGN_NAME] = sign
    } else {
        if (config.data instanceof FormData) {
            // config.data.append('timestamp', new Date().getTime())
            // let sign = utils.getSign(utils.formDataToObject(config.data, true))
            // config.data.append(constants.PARAM_SIGN_NAME, sign)
        } else {
            config.data = config.data || {}
            config.data = serializeParams(config.data) // 序列化请求参数
            config.data['timestamp'] = new Date().getTime()
            sign = utils.getSign(config.data)
            config.data[constants.PARAM_SIGN_NAME] = sign
            config.data = querystring.stringify(config.data)
        }
    }
    return config
}, function(error) {
    return Promise.reject(error)
})

// 响应拦截
axios.interceptors.response.use(function(resp) {
    console.log("request success: ", resp.data)
    if (!Store.state.isManualCloseLoading) {
        Store.dispatch('showLoading', false)
    }
    if (resp.data.code == constants.REQUEST_API_TOKEN_INVALID) { // 会话超时
        EventBus.dispatch(constants.EVENT_API_TOKEN_INVALID)
        return Promise.reject(resp.data.message)
    } else if (resp.data.code != constants.REQUEST_SUCCESS) {
        Store.dispatch('showToast', resp.data.message)
        return Promise.reject(resp.data)
    }
    return resp.data
}, function(error) {
    console.warn("request error: ", error)
    if (!Store.state.isManualCloseLoading) {
        Store.dispatch('showLoading', false)
    }
    let message
    if (error.response && error.response.status >= 500 && error.response.status < 599) {
        message = "服务器异常"
    } else {
        if (error.message.indexOf('timeout') != -1) {
            message = "请求超时"
        } else {
            message = "操作失败"
        }
    }
    Store.dispatch('showToast', message)
    return Promise.reject(message)
})